package cn.smile.commons.encrypt;

import cn.smile.commons.encrypt.service.EncryptService;
import cn.smile.utils.SpringContextUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.ObjectUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@SuppressWarnings("unchecked")
public class EncryptTypeHandler<T> extends BaseTypeHandler<T> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, this.getEncryptService().encrypt((String) parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        //有一些可能是空字符
        return ObjectUtils.isEmpty(columnValue) ? (T) columnValue : (T) this.getEncryptService().decrypt(columnValue);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        return ObjectUtils.isEmpty(columnValue) ? (T) columnValue : (T) this.getEncryptService().decrypt(columnValue);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String columnValue = cs.getString(columnIndex);
        return ObjectUtils.isEmpty(columnValue) ? (T) columnValue : (T) this.getEncryptService().decrypt(columnValue);
    }

    /**
     * 获取Spring容器中的 encryptService Bean
     *
     * @return Bean对象
     */
    private EncryptService getEncryptService() {
        return (EncryptService) SpringContextUtils.getBean("encryptService");
    }
}
